package cn.wsn2018.tools.ctrl;

import cn.wsn2018.tools.model.SystemConfig;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.service.SecUserService;
import cn.wsn2018.tools.util.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @program: tools
 * @description
 * @author: songDaisong
 * @create: 2020-01-02 20:46
 **/
@RestController
@RequestMapping("/protocol")
public class SecUserController {

    @Autowired
    private SecUserService secUserService;
    private static final Logger logger = LoggerFactory.getLogger(SecUserController.class);

    @CrossOrigin
    @RequestMapping(value = "/secusers",method = RequestMethod.POST)
    public void createUser(@RequestBody User user,
                           @RequestParam("usrname")String username,
                           @RequestParam("token")String token,
                           HttpServletResponse response,
                           HttpServletRequest request) throws Exception {
        /**
        * @Description:  保存新增用户
        * @Param: [user, username, token, response, request]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/2/4 16:22
        */
        //用户角色判断
            String msg = secUserService.save(username,user,token,request);
            ServletUtil.getInstance().responseOperating(response, msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/checkusernameavailable",method = RequestMethod.GET)
    public void checkUsrnameAvailable(@RequestParam("username") String username,
            @RequestParam("token")String token, HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  查询用户名是否可用
        * @Param: [username, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/5 16:34
        */
        String msg = secUserService.checkUsernameAvailable(username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/listsecusers",method = RequestMethod.GET)
    public void listSecUsers(@RequestParam("pageNum") String pageNum,
                                @RequestParam("pageSize") String pageSize,
                                @RequestParam(value = "role",required = false,defaultValue = "") String role,
                                @RequestParam(value = "type",required = false,defaultValue = "")String type,
                                @RequestParam(value = "state",required = false,defaultValue = "")String state,
                                @RequestParam(value = "lock",required = false,defaultValue = "")String lock,
                                @RequestParam(value = "permission",required = false,defaultValue = "")String permission,
                                @RequestParam(value = "username",required = false,defaultValue = "")String username,
                                @RequestParam("token")String token,
                                @RequestParam("click")Boolean click,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        /**
        * @Description:  查询用户
        * @Param: [pageNum, pageSize, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/5 16:34
        */
        String msg = secUserService.listSecUsers(pageNum, pageSize,role,type,state,username,lock,permission,token,request,click);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/removesecuser",method = RequestMethod.POST)
    public void removeSecUserById(@RequestParam("id")String id,
                                  @RequestParam("username")String username,
                                  @RequestParam("token")String token, HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  注销用户
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/9 19:46
        */
        String msg = secUserService.removeSecUserById(id,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);

    }

    @CrossOrigin
    @RequestMapping(value = "/activesecuser",method = RequestMethod.POST)
    public void activeSecUserById(@RequestParam("id")String id,@RequestParam("username") String username,
                                  @RequestParam("token")String token,
                                  HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  激活用户
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/9 19:46
        */
        String msg = secUserService.activeSecUserById(id,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }


    //@CrossOrigin
    //@RequestMapping(value = "/locksecuser",method = RequestMethod.PUT)
//    public void lockSecUserById(@RequestParam("id")String id,
//                                @RequestParam("token")String token,
//                                HttpServletRequest request,HttpServletResponse response) throws Exception {
//        /**
//        * @Description:  加锁,不用
//        * @Param: [id, response]
//        * @return: void
//        * @Author: SongDaisong
//        * @Date:  2020/1/9 19:45
//        */
//        String msg = secUserService.lockSecUserById(id,token,request);
//        ServletUtil.getInstance().responseOperating(response,msg);
//    }

    @CrossOrigin
    @RequestMapping(value = "/unlocksecuser",method = RequestMethod.POST)
    public void unlockSecUserById(@RequestParam("id")String id,@RequestParam("username") String username,
                                  @RequestParam("token") String token,
                                  HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  解锁
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/9 19:45
        */
        String msg = secUserService.unlockSecUserById(id,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/givepermissionsecuser",method = RequestMethod.POST)
    public void givePermissionSecUserById(@RequestParam("id")String id,@RequestParam("username")String username,
                                          @RequestParam("token")String token,
                                          HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  授权
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/9 19:47
        */
        String msg = secUserService.givePermissionSecUserById(id,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/removepermissionsecuser",method = RequestMethod.POST)
    public void removePermissionSecUserById(@RequestParam("id")String id,@RequestParam("username")String username,
                                            @RequestParam("token")String token,
                                            HttpServletRequest request,HttpServletResponse response) throws Exception {
        /** 
        * @Description: 取消授权 
        * @Param: [id, username, token, request, response] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/4/22 19:45
        */ 
        String msg = secUserService.removePermissionSecUserById(id, username, token, request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }


    @CrossOrigin
    @RequestMapping(value = "/restsecuserpassword",method = RequestMethod.POST)
    public void resetSecUserPasswordByid(@RequestParam("id")String id,@RequestParam("username")String username,
                                         @RequestParam("token")String token,
                                         HttpServletRequest request,HttpServletResponse response) throws Exception{
        /**
        * @Description:  重置密码
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/9 19:47
        */
        String msg = secUserService.resetSecUserPasswordByid(id,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/getsecuserbyid",method = RequestMethod.GET)
    public void getSecUserById(@RequestParam("id")String id,@RequestParam("token")String token,
                               HttpServletRequest request,HttpServletResponse response) throws Exception {
        /**
        * @Description:  根据用户id获取用户信息
        * @Param: [id, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/1/12 13:48
        */
        String msg = secUserService.getSecUserById(id,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    /**
     * @Description: 用户信息修改
     * @Param: [id, idCard, phone, role, type, accesssTime, ipAddress, response]
     * @return: void
     * @Author: SongDaisong
     * @Date:  2020/1/20 22:20
     */
    @CrossOrigin
    @RequestMapping(value = "/updatesecuserinfo",method = RequestMethod.POST)
    public void updateSecUserInfo(@RequestParam("id")String id,
                                  @RequestParam("idCard")String idCard,
                                  @RequestParam("phone")String phone,
                                  @RequestParam("role")String role,
                                  @RequestParam("type")Integer type,
                                  @RequestParam("accessTime")Integer accesssTime,
                                  @RequestParam("ipAddress")String ipAddress,
                                  @RequestParam("username")String username,
            @RequestParam("token")String token,HttpServletRequest request
            ,HttpServletResponse response) throws Exception {
        String msg = secUserService.updateSecUserInfo(id, idCard, phone, role, type, accesssTime, ipAddress,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    /**
     * @Description: 更新系统配置
     * @Param: [systemConfig, response]
     * @return: void
     * @Author: SongDaisong
     * @Date:  2020/1/20 22:48
     */
    @CrossOrigin
    @RequestMapping(value = "/updatesystemconfig",method = RequestMethod.POST)
    public void updateSystemConfig(@RequestBody SystemConfig systemConfig, @RequestParam("username")String username,
                                   @RequestParam("token")String token, HttpServletRequest request,HttpServletResponse response) throws Exception {

//        SystemConfig config=systemConfig;
//        //根据系统管理员配置来设置会话超时时间
//        Integer sessionOutOfTime=Integer.parseInt(config.getSessionMaxOverTime());
//        //增加系统会话超时时间
//        CommonValue.SESSION_OUT_OF_TIME=sessionOutOfTime*60;
//        logger.info("SessionMaxOverTime："+CommonValue.SESSION_OUT_OF_TIME+",config Time:"+sessionOutOfTime);
//        HttpSession session=request.getSession(true);
//        session.setMaxInactiveInterval(CommonValue.SESSION_OUT_OF_TIME);
        String msg = secUserService.updateSystemConfig(systemConfig,username,token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/getsystemconfig",method = RequestMethod.GET)
    public void getSystemConfig(@RequestParam("token")String token,
                                HttpServletRequest request,HttpServletResponse response)throws Exception{
        /** 
        * @Description: 获取系统配置 
        * @Param: [token, request, response] 
        * @return: void 
        * @Author: SongDaisong
        * @Date:  2020/3/17 21:58
        */ 
        String msg = secUserService.getSystemConfig(token,request);
        ServletUtil.getInstance().responseOperating(response,msg);
    }
    

    //以下是不用进行角色判断的
    @CrossOrigin
    @RequestMapping(value = "/producewarning",method = RequestMethod.POST)
    public void produceUrlWarningLog(@RequestParam("username") String username,
                                  @RequestParam("urlPathname")String urlPathname,
                                  @RequestParam("token")String token,
                                  HttpServletRequest httpServletRequest) throws Exception {
        /** 
        * @Description: url越权信息日志生成接口，不用做校验
        * @Param: [username, urlPathname, httpServletRequest] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/2/4 18:29
        */
        if(!StorageUtil.isInLoginSessions(username,token)){
            //用户未登录情况下，复制粘贴
            return;
        }
        if(StringUtil.isEmptyString(username)){
            username=ServletUtil.getUserNameByToken(token);
        }
        secUserService.produceUrlWarningLog(username,urlPathname,httpServletRequest);
        //用户被强迫下线
        StorageUtil.getInstance().removeSessions(token);

        //防止内存泄露
        ThreadLocal<String> localUserName = ThreadUtil.getThreadLocalUserName();
        localUserName.remove();

    }

    @CrossOrigin
    @RequestMapping(value = "/checkauthorizationstate",method = RequestMethod.GET)
    public void checkAuthorizationState(@RequestParam("username") String username,
                                        @RequestParam("token")String token,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        /**
        * @Description:  检测用户是否授权，不做用户角色判断，因为每个用户都可能用到，不会越权
        * @Param: [username, token, request, response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/2/4 17:10
        */
        String msg = secUserService.getAuthorizationState(username);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

    @CrossOrigin
    @RequestMapping(value = "/askauthorized",method = RequestMethod.POST)
    public void askPermissionSecUserByName(@RequestParam("username") String username,HttpServletResponse response) throws Exception {
        /** 
        * @Description: 用户请求授权
        * @Param: [username, response] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/2/4 18:11
        */ 
        String msg = secUserService.askPermissionSecUserByName(username);
        ServletUtil.getInstance().responseOperating(response,msg);
    }


    @CrossOrigin
    @RequestMapping(value = "/getsleepuseroveryear",method = RequestMethod.GET)
    public void getSleepUserOverYear(@RequestParam("token")String token,@RequestParam("timeStamp") String timeStamp,
                                     HttpServletResponse response) throws Exception {
        /**
        * @Description: 查询当前是否有休眠用户处于休眠期快一年，给弹窗提示
        * @Param: [response]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/4/13 21:10
        */
        if(!CheckUserTimeStamp.isValidateQuery(token,timeStamp)){
            //如果用户两次请求时间太短，就不允许执行
            return;
        }
        String msg = secUserService.getSleepUserOverYear();
        ServletUtil.getInstance().responseOperating(response, msg);
    }


    @CrossOrigin
    @RequestMapping(value = "/isonline",method = RequestMethod.GET)
    public void isOnline(@RequestParam("token")String token,
                         @RequestParam("username")String username,
                         HttpServletResponse response) throws Exception {
        /** 
        * @Description: 判断用户是否在线
        * @Param: [token, username, response] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/5/1 13:21
        */ 


        String msg=secUserService.isOneline(token,username);
        ServletUtil.getInstance().responseOperating(response,msg);
    }

}
